import { useUserStore } from '@/store/user/index'

uni.addInterceptor('request', {
  invoke(option: UniApp.RequestOptions) {
    const userStore = useUserStore()
    // console.log(userStore.tenantId)
    if (userStore.tenantId) {
      option.header = {
        ...option.header,
        __tenant: userStore.tenantId
      }
    } else {
      uni.showToast({
        title: '请先确认所属单位',
        icon: 'error'
      })
    }
    if (!option.url.startsWith('http')) {
      option.url = import.meta.env.VITE_BASEURL + option.url
    }
    option.timeout = 10000
  }
})

export const http = <T>(option: UniApp.RequestOptions): Promise<T> => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...option,
      success: res => {
        if (
          res.statusCode === 200 ||
          res.statusCode === 201 ||
          res.statusCode === 202 ||
          res.statusCode === 203 ||
          res.statusCode === 204 ||
          res.statusCode === 206
        ) {
          resolve(res.data as T)
        } else {
          if (res.statusCode === 403) {
            console.log(res)
            uni.showToast({
              title: res.data.error.message,
              icon: 'error'
            })
          }
          reject(res.data)
        }
      },
      fail: err => {
        console.log(err.errMsg)
        reject(err)
      }
    })
  })
}
